package com.ruoyi.project.applet.service.impl;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.applet.domain.*;
import com.ruoyi.project.applet.mapper.CollectMapper;
import com.ruoyi.project.applet.mapper.InteractMapper;
import com.ruoyi.project.applet.mapper.OrderMapper;
import com.ruoyi.project.applet.service.InteractService;
import com.ruoyi.project.applet.service.RecordService;
import com.ruoyi.project.system.domain.SysUserWx;
import com.ruoyi.project.system.service.impl.SysUserWxServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InteractServiceImpl implements InteractService {

    private final Logger logger = LoggerFactory.getLogger("InteractServiceImpl");


    @Resource
    private InteractMapper interactDao;

    @Resource
    private RecordService recordService;

    @Autowired
    private SysUserWxServiceImpl sysUserWxService;

    @Autowired
    private CollectMapper collectMapper;


    @Autowired
    private WalletServiceImpl walletService;

    @Autowired
    private WechatPayNewServer wechatPayNewServer;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Integer add(Integer from_id, Integer to_id, Integer l_count, String l_lastTime, String l_lastcontent, Integer l_type, String chatid) {
        return interactDao.add(from_id, to_id, l_count, l_lastTime, l_lastcontent, l_type, chatid);
    }

    @Override
    public Interact isrecord(Integer from_id, Integer to_id) {
        return interactDao.isrecord(from_id, to_id);
    }

    @Override
    public Integer update(Integer from_id, Integer to_id, Integer l_count, String l_lastTime, String l_lastcontent, Integer l_type) {
        return interactDao.update(from_id, to_id, l_count, l_lastTime, l_lastcontent, l_type);
    }

    @Override
    public Integer updatecount(Integer from_id, Integer to_id) {
        return interactDao.updatecount(from_id, to_id);
    }

    @Override
    public AjaxResult selectByto_id(Long to_id) throws ParseException {
        List<Interact> lisus = interactDao.selectByto_id(to_id);//查询当前用户所有的聊天列表
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < lisus.size(); i++) {
            JSONObject jsonObject = new JSONObject();//创建一个json对象
            Interact lisu = lisus.get(i);//遍历出来所有数据
            long from_id = lisu.getFromId();//查找谁发的消息
            long l_count = lisu.getCount();//未读总条数
            String l_lastcontent = lisu.getLastContent();//最后一条聊天内容
            String l_lastTime = DateUtil.format(lisu.getLastTime(), "yyyy-MM-dd");
            String chatid = lisu.getChatId();//会话id
            // Account user = accountDao.selectAccountById(from_id);//查找谁发的消息的用户信息
            SysUserWx user = sysUserWxService.selectSysUserWxById(from_id);

            String avatar = user.getAvatar();//头像
            String nickname = user.getNickName();//昵称
            jsonObject.fluentPut("avatar", avatar);
            jsonObject.fluentPut("nickname", nickname);
            jsonObject.fluentPut("l_lastcontent", l_lastcontent);
            jsonObject.fluentPut("l_lastTime", l_lastTime);
            jsonObject.fluentPut("l_count", l_count);
            jsonObject.fluentPut("chatid", chatid);
            jsonObject.fluentPut("from_id", from_id);
            jsonArray.add(jsonObject);//存进数组
        }

        return AjaxResult.success(jsonArray);
    }

    @Override
    public AjaxResult selectCount(Long to_id) {
        Map<Object, Object> result = new HashMap<>();
        //设置未读消息数量
        Integer count = interactDao.selectCount(to_id);
        if (count == null) {
            result.put("msg", 0);
        } else {
            result.put("msg", count);
        }
        //设置营销客户数量
        SysUserWx sysUserWx = sysUserWxService.selectSysUserWxById(to_id);
        Order query = new Order();
        query.setFirstParent(sysUserWx.getOpenId());
        List<Order> orderList = orderMapper.selectOrderList(query);
        //根据userId去重
        List<String> userList = orderList.stream().map(Order::getOpenId).distinct().collect(Collectors.toList());
        result.put("marketing", userList.size());
        //设置我的收藏数量
        Collect collect = new Collect();
        collect.setUserId(sysUserWx.getOpenId());
        List<Collect> collectList = collectMapper.selectCollectList(collect);
        result.put("collect", collectList.size());
        //设置抽奖点数
        Wallet wallet = walletService.getWalletMoney(sysUserWx.getOpenId());
        result.put("wallet", wallet.getNumber());
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult insertInteract(String ss, Long userId) {
        System.out.println("ss:" + ss);
        try {
            JSONObject jsonObject = JSONObject.parseObject(ss);//转json
            Integer u_id = userId.intValue();
            if (jsonObject.getString("type").equals("msg") || jsonObject.getString("type") == "msg") {
                //第一种类型，发送消息
                if (null == jsonObject.getInteger("to")) {
                    //操作错误
                    throw new BaseException("操作失败");
                } else {
                    Integer u_id1 = jsonObject.getInteger("to");
                    String content = jsonObject.getString("content");
                    Integer content_type = jsonObject.getInteger("content_type");
//                        Integer from = jsonObject.getInteger("from");
                    SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
                    sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
                    Date date = new Date();
                    String time = sdf.format(date);

                    long count = recordService.isrecord(u_id, u_id1);
                    long count1 = recordService.isrecord(u_id1, u_id);
                    String chatid = null;
                    if (count == 0 && count1 == 0) {//俩人第一次聊天
                        //获取随机字符串   会话id
                        String str = "0123456789abcdefghijklmnopqrstuvwxyz";
                        Random random = new Random();
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < 3; i++) {
                            int number = random.nextInt(10);
                            sb.append(str.charAt(number));
                        }
                        chatid = sb + String.valueOf(u_id) + String.valueOf(u_id1);
                        recordService.add(u_id, u_id1, content, content_type, chatid, time);//添加消息记录
                        if (content_type == 2) {
                            //内容是图片
                            add(u_id, u_id1, 1, time, "[图片]", content_type, chatid);//添加聊天列表
                            add(u_id1, u_id, 0, time, "[图片]", content_type, chatid);
                        } else {
                            add(u_id, u_id1, 1, time, content, content_type, chatid);//添加聊天列表
                            add(u_id1, u_id, 0, time, content, content_type, chatid);
                        }
                    } else {
                        //俩人不是第一次聊天
                        chatid = isrecord(u_id, u_id1).getChatId();//获取两个人的会话id
                        recordService.add(u_id, u_id1, content, content_type, chatid, time);//添加消息记录
                        Integer l_count = Math.toIntExact(isrecord(u_id, u_id1).getCount());//获取当前唯独条数
                        Integer l_count1 = Math.toIntExact(isrecord(u_id1, u_id).getCount());//获取当前唯独条数
                        if (content_type == 2) {
                            //内容是图片
                            update(u_id, u_id1, l_count + 1, time, "[图片]", content_type);//修改聊天列表
                            update(u_id1, u_id, l_count1, time, "[图片]", content_type);
                        } else {
                            update(u_id, u_id1, l_count + 1, time, content, content_type);//修改聊天列表
                            update(u_id1, u_id, l_count1, time, content, content_type);//修改聊天记录
                        }
                    }
                    sendInfo(u_id1, u_id, content, content_type, time);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BaseException("操作失败");
        }
        return AjaxResult.success();
    }

    // 给指定用户发送信息  ,Integer from
    public void sendInfo(Integer id, Integer from, String content, Integer content_type, String time) {
        JSONObject jsonObject = new JSONObject();//创建一个json对象
        jsonObject.fluentPut("type", "msg");
        jsonObject.fluentPut("content", content);
        jsonObject.fluentPut("from", from);
        jsonObject.fluentPut("to", id);
        jsonObject.fluentPut("content_type", content_type);
        jsonObject.fluentPut("time", time);
        try {
            sendMessage(jsonObject, id);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BaseException("信息发送失败");
        }
    }

    // 发送消息
    public void sendMessage(Object object, Integer u_id) throws IOException {
        List<Record> records = recordService.selectByIssend(u_id);
        for (int i = 0; i < records.size(); i++) {
            Record record = records.get(i);
            Integer r_id = Math.toIntExact(record.getRecordId());//id
            recordService.updateById(r_id);//通过id修改消息为已发送
        }
    }
}
